<!-- Including InstantSearch.js library and styling -->
<script src="https://cdn.jsdelivr.net/npm/instantsearch.js@2.6.0/dist/instantsearch.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<link
  rel="stylesheet"
  type="text/css"
  href="https://cdn.jsdelivr.net/npm/instantsearch.js@2.6.0/dist/instantsearch.min.css"
/>
<link
  rel="stylesheet"
  type="text/css"
  href="https://cdn.jsdelivr.net/npm/instantsearch.js@2.6.0/dist/instantsearch-theme-algolia.min.css"
/>

<div id="search-searchbar"></div>
<div class="post-list" id="search-hits"></div>

<script>
  const search = instantsearch({
    appId: '{{ .Site.Params.algolia_appId }}',
    indexName: '{{ .Site.Params.algolia_indexName }}',
    apiKey: '{{ .Site.Params.algolia_apiKey }}'
  });
  const hitTemplate = function(hit) {
    let date = '';
    if (hit.date) {
      date = moment.unix(hit.date).format('MMM D, YYYY');
    }
    let url = `${hit.url}#${hit.anchor}`;
    const title = hit._highlightResult.title.value;
    let breadcrumbs = '';
    if (hit._highlightResult.headings) {
      breadcrumbs = hit._highlightResult.headings
        .map(match => {
          return `<span class="post-breadcrumb">${match.value}</span>`;
        })
        .join(' > ');
    }
    let content = '';
    if (hit._highlightResult.content) {
      content = hit._highlightResult.content.value;
    } else {
      content = hit.summary;
    }
    return `
    <div class="post-item">
      <span class="post-meta">${date}</span>
      <h2><a class="post-link" href="${url}">${title}</a></h2>
      <a href="${url}" class="post-breadcrumbs">${breadcrumbs}</a>
      <div class="post-snippet">${content}</div>
    </div>
  `;
  };
  search.addWidget(
    instantsearch.widgets.searchBox({
      container: '#search-searchbar',
      placeholder: '搜索',
      poweredBy: true // This is required if you're on the free Community plan
    })
  );
  search.addWidget(
    instantsearch.widgets.hits({
      container: '#search-hits',
      templates: {
        item: hitTemplate
      }
    })
  );
  search.start();
</script>

<style>
  #search-searchbar {
    margin-top: 40px;
  }
  .ais-search-box {
    max-width: 100%;
    margin-bottom: 15px;
  }
  .post-item {
    margin-bottom: 30px;
  }
  .post-link .ais-Highlight {
    color: #111;
    font-style: normal;
    text-decoration: underline;
  }
  .post-breadcrumbs {
    color: #424242;
    display: block;
  }
  .post-breadcrumb {
    font-size: 18px;
    color: #424242;
  }
  .post-breadcrumb .ais-Highlight {
    font-weight: bold;
    font-style: normal;
  }
  .post-snippet .ais-Highlight {
    color: #2a7ae2;
    font-style: normal;
    font-weight: bold;
  }
  .post-snippet img {
    display: none;
  }
</style>
